package com.codemonkey.lq.qd.builder.xml;

import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.parsing.XNode;

import com.codemonkey.lq.qd.builder.BaseBuilder;
import com.codemonkey.lq.qd.facotry.config.AbstractServiceDefinition;
import com.codemonkey.lq.qd.facotry.config.SConfiguration;
import com.codemonkey.lq.qd.facotry.support.GenericServiceDefinition;

/**
 * 用于解析单个service配置文件
 * 类似MyBatis中<mapper/>下的<insert/><update/><delete/><select/>的解析
 * @author LQ
 */
public class XMLServiceBuilder extends BaseBuilder {
	
	public static final String ID_ATTRIBUTE = "id";
	
	private XNode context;
	private String resource;

	XMLMapperBuilder d;

	public XMLServiceBuilder(XNode context, SConfiguration configuration, String resource) {
		super(configuration);
		this.context = context;
		this.resource = resource;
	}

	@Override
	protected Object doParse() {
		String id = context.getStringAttribute("id");

		AbstractServiceDefinition sd = new GenericServiceDefinition(configuration);
		sd.setId(id);

		configuration.addServiceDefinition(sd);

		actionListElement(sd, context.evalNode("action-list"));
		flowListElement(sd, context.evalNode("flow-list"));

		return sd;
	}

	private void actionListElement(AbstractServiceDefinition sd, XNode evalNodeList) {
		if (null == evalNodeList) {
			return;
		}

		for (XNode actionContext : evalNodeList.evalNodes("action")) {
			XMLActionBuilder builder = new XMLActionBuilder(actionContext, sd, configuration);
			builder.parse();
		}
	}

	private void flowListElement(AbstractServiceDefinition sd, XNode evalNodeList) {
		if (null == evalNodeList) {
			return;
		}
		for (XNode flowContext : evalNodeList.evalNodes("flow")) {
			XMLFlowBuilder builder = new XMLFlowBuilder(flowContext, sd, configuration);
			builder.parse();
		}
	}

}
